﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ReporterEngine.Methods
{
    public class DescBy : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.Method && !string.IsNullOrEmpty(token.PathExp) && token.PathExp.ToLower() == "descby";
        }

        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();

            foreach (var element in query.Elements)
            {
                result.Elements.Add(element);
            }
                       

          //  var propertiesName = query.GetArgValuesForType(token);

           // var lowerPropertyname = propertiesName[0].ToLower();

            //sQuery propQuery = Interpreter.Execute(token.Args[0], result);

            //foreach (var resEl in propQuery.Elements)
            //{
            //    var ii = 12;
            //}

            result.Elements = result.Elements.OrderByDescending(SortFunction(token, query)).ToList();

            return result;
        }

        private Func<System.Xml.Linq.XElement, string> SortFunction(LexPath.PathToken token, sQuery query)
        {
            return x => GetPropertyValue(token, query, x);
        }

        private string GetPropertyValue(LexPath.PathToken token, sQuery query, XElement element)
        {
            var tempQuery = query.New();
            tempQuery.Elements.Add(element);

            var res = Interpreter.Execute(token.Args[0], tempQuery).Value;
           return res;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[] { new MethodDescription { Name = "descby" } };
        }
    }
}
